import React, { useRef, useState } from 'react'
import {
  postCompanyInfoDetailPatentGroupByDateType,
  postCompanyInfoDetailPatentGroupByType,
  postCompanyInfoDetailPatentPageList
} from '@/api/companyDetail/intellectual-property'
import { DetailModal } from '@hs-server/components'
import { useNewPage } from '@hs-admin/utils'
import { HsAdminTablePage } from '@hs-admin/base-components'
import HSGlobalPieChart from '@/utils/chart/global-pie-chart'
import { HsGlobalCircleBarChart } from '@/utils/chart/global-bar-chart'
import './style.less'

const Patent = (props: any) => {
  const { companyCode, hiddenModule }: any = props
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 80,
      render: (_: string, _record: any, index: number) => <>{index + 1 + (pagination.current - 1) * pagination.pageSize}</>
    },
    {
      title: '专利名称',
      dataIndex: 'title',
      width: 200,
      render: (text: string, record: any) => (
        <span
          className="link cursor-pointer"
          onClick={() => {
            record.eventSubType = '知识产权'
            record.eventSegment = record.patentType
            DetailModalRef.current.showModal(record)
          }}>
          {text}
        </span>
      ),
      ellipsis: true
    },
    {
      title: '专利类型',
      dataIndex: 'patentType'
    },
    {
      title: '法律状态',
      dataIndex: 'legalState'
    },
    {
      title: '是否PCT专利',
      dataIndex: 'pct',
      render: (text: string) => <>{text ? '是' : '否'}</>
    },
    {
      title: '申请号',
      dataIndex: 'applicationCode'
    },
    {
      title: '申请日',
      dataIndex: 'applicationDate'
    },
    {
      title: '公开日',
      dataIndex: 'publicationDate'
    },
    {
      title: '公开号',
      dataIndex: 'publicationCode'
    }
  ]
  const { pagination } = useNewPage(callList)
  const [data, setdata] = useState([])
  const DetailModalRef = useRef<any>({})
  const pieData = useRef([
    { value: 0, name: '发明专利/发明授权', unit: '件' },
    { value: 0, name: '实用新型', unit: '件' },
    { value: 0, name: '外观专利', unit: '件' }
  ])
  const [isShow, setIsShow] = useState(false)
  const [iscount, setiscount] = useState('')
  const [showPie, setshowPie] = useState(false)
  const [showBar, setshowBar] = useState(false)
  const [loading, setloading] = useState(false)

  function callList() {
    setloading(true)
    return postCompanyInfoDetailPatentPageList({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      companyCode: companyCode || 'c55c12bf062e40fd283c87726d053387'
    })
      .then((res: { data: { list: React.SetStateAction<never[]>; total: any } }) => {
        setdata(res.data.list)
        res.data.total = Number(res.data.total) > 10000 ? 10000 : res.data.total
        setIsShow(res.data.total ? true : false)
        setiscount(res.data.total ?? '')
        hiddenModule(res.data.total ?? '') //总条数 传给父组件
        callPieList()
        callBarList()
        return res.data
      })
      .finally(() => {
        setloading(false)
      })
  }
  function initPie(dom: string, data: any[]) {
    if (!document.getElementById(dom)) {
      return
    }
    if (!data.length) {
      return
    }
    const chartInstance = new HSGlobalPieChart({
      dom,
      color: ['#59CB75', '#FA885D', '#FFC64C'],
      legend: {
        orient: 'vertical',
        top: 'middle',
        right: '8%',
        data,
        show: false
      },
      tooltip: {
        trigger: 'item',
        formatter: (params: { marker: string; data: { name: string; value: number }; percent: number }) => {
          return `<div>
            <p>${params.marker}${params.data.name}</p>
            <div >
                &nbsp;&nbsp;&nbsp;<span class="tooltip_text">数量 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span style="font-weight: bold;color: #333333;">${params.data.value}</span>  件</span></br>
                &nbsp;&nbsp;&nbsp;<span class="tooltip_text">占比 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span style="font-weight: bold;color: #333333;">${params.percent}   %</span></span>
            </div>
          </div>`
        }
      },
      series: [
        {
          radius: ['55%', '70%'],
          center: ['50%', 'center'],
          data
        }
      ]
    })
    return chartInstance
  }
  function callPieList() {
    postCompanyInfoDetailPatentGroupByType({
      companyCode: companyCode || 'c55c12bf062e40fd283c87726d053387'
    }).then((res) => {
      const { data } = res
      data['发明专利/发明授权'] = (data['发明授权'] || 0) + (data['发明专利'] || 0)
      pieData.current.forEach((item) => {
        item.value = data[item.name]
      })
      pieData.current = pieData.current.filter((item) => item.value)
      setshowPie(!!pieData.current.length)
      if (pieData.current.length) {
        setTimeout(() => {
          initPie('pie-chart', pieData.current)
        })
      }
    })
  }
  function initBar(
    dom: string,
    xAxisData: any[],
    legendData: string[],
    seriesData1: any[],
    seriesData2: any[],
    seriesData3: any[],
    totalList: any[]
  ) {
    if (!document.getElementById(dom)) {
      return
    }
    if (!xAxisData.length) {
      return
    }
    const chartInstance = new HsGlobalCircleBarChart({
      dom,
      color: ['#59CB75', '#FA885D', '#FFC64C'],
      legend: {
        show: true, //是否显示
        data: legendData,
        bottom: '0%',
        left: '0%',
        itemGap: 20
      },
      xAxis: {
        data: xAxisData,
        axisLabel: {
          fontSize: 12
        }
      },
      yAxis: {
        name: '单位：件',
        valueData: totalList
      },
      series: [
        {
          name: '发明专利/发明授权',
          data: seriesData1,
          stack: '专利信息',
          colorList: ['#59CB75', '#59CB75']
        },
        {
          name: '实用新型',
          data: seriesData2,
          stack: '专利信息',
          colorList: ['#FA885D', '#FA885D']
        },
        {
          name: '外观专利',
          data: seriesData3,
          stack: '专利信息',
          colorList: ['#FFC64C', '#FFC64C'],
          itemStyle: {
            borderRadius: [6, 6, 0, 0]
          }
        }
      ]
    })
    return chartInstance
  }
  function callBarList() {
    // 柱状图
    return postCompanyInfoDetailPatentGroupByDateType({
      companyCode: companyCode || 'c55c12bf062e40fd283c87726d053387'
    }).then((res) => {
      const { data } = res
      const xAxisData = data.map((item: { key: any }) => item.key)
      const legendData: string[] = []
      const seriesData1 = data.map(
        (item: { children: any[] }) =>
          (item.children.filter((el) => el.key === '发明专利')[0]?.value || 0) + (item.children.filter((el) => el.key === '发明授权')[0]?.value || 0)
      )
      const seriesData2 = data.map((item: { children: any[] }) => {
        return item.children.filter((el) => el.key === '实用新型')[0]?.value ?? 0
      })
      const seriesData3 = data.map((item: { children: any[] }) => {
        return item.children.filter((el) => el.key === '外观专利')[0]?.value ?? 0
      })
      if (seriesData1.some((item: number) => item)) {
        legendData.push('发明专利/发明授权')
      }
      if (seriesData2.some((item: number) => item)) {
        legendData.push('实用新型')
      }
      if (seriesData3.some((item: number) => item)) {
        legendData.push('外观专利')
      }
      const totalList: string | any[] = []
      for (const [key, item] of seriesData1.entries()) {
        totalList[key] = item + seriesData2[key] + seriesData3[key]
      }
      setshowBar(!!totalList.length)
      if (totalList.length) {
        setTimeout(() => {
          initBar('bar-chart', xAxisData, legendData, seriesData1, seriesData2, seriesData3, totalList)
        })
      }
    })
  }

  return (
    <>
      {isShow && (
        <div className="intellectual-property-patent-wrapper" id="专利信息" data-count={iscount}>
          <h3 className="mb-2">专利信息</h3>
          {(showPie || showBar) && (
            <div className="chart-box">
              {showPie && <div className="pie-chart" id="pie-chart"></div>}
              {showBar && <div className="bar-chart" id="bar-chart"></div>}
            </div>
          )}
          <HsAdminTablePage
            columns={columns}
            dataSource={data}
            id="intellectual-property-patent"
            pagination={pagination}
            rowKey={(record: { id: string }) => record.id}
            size="small"
            loading={loading}
          />
          <DetailModal ref={DetailModalRef} />
        </div>
      )}
    </>
  )
}

export default Patent
